<template>
  <div class="shop-order-edit">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>基础信息</span>
        </div>
      </template>
      <el-form :model="shopOrderForm" ref="shopOrderFormRef" label-width="100px" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售单号" prop="shopOrderCode" required>
              <el-input v-model="shopOrderForm.shopOrderCode" placeholder="自动获取系统编号" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售日期" prop="shopOrderDate" required>
              <el-date-picker
                v-model="shopOrderForm.shopOrderDate"
                type="date"
                placeholder="请选择"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerId" required>
              <el-select
                v-model="shopOrderForm.customerId"
                placeholder="请选择"
                style="width: 100%"
                @change="handleCustomerChange"
                filterable
              >
                <el-option
                  v-for="item in customerOptions"
                  :key="item.id"
                  :label="item.customerName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="shopOrderForm.contact" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactPhone">
              <el-input v-model="shopOrderForm.contactPhone" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售部门" prop="deptId" required>
              <el-tree-select
                v-model="shopOrderForm.deptId"
                :data="departmentOptions"
                placeholder="请选择"
                check-strictly
                node-key="value"
                :props="{
                  label: 'label',
                  children: 'children',
                }"
                @change="handleDeptChange"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售负责人" prop="userId" required>
              <el-select 
                v-model="shopOrderForm.userId" 
                placeholder="请选择" 
                style="width: 100%" 
                @change="handleUserChange"
                filterable
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.user_Id || item.user_ID"
                  :label="item.userName"
                  :value="item.user_Id || item.user_ID"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="shopOrderForm.remark" type="textarea" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>销售货品明细</span>
        </div>
      </template>

      <div class="button-container">
        <el-button type="success" @click="openGoodsDialog">添加</el-button>
        <el-button type="danger" @click="removeSelectedItems">移除</el-button>
      </div>

      <el-table
        :data="shopOrderDetails"
        style="width: 100%; margin-top: 10px"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column prop="goodsName" label="货品名称" min-width="120" />
        <el-table-column prop="goodsCode" label="货品编号" min-width="120" />
        <el-table-column prop="specModel" label="规格型号" min-width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="currentInventory" label="当前库存" width="100" />
        <el-table-column label="货品数量" width="120" required>
          <template #default="scope">
            <el-input-number
              v-model="scope.row.shopOrderNum"
              :min="1"
              @change="calculateItemAmount(scope.row)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="销售单价" width="120" required>
          <template #default="scope">
            <el-input-number
              v-model="scope.row.shopOrderPrice"
              :precision="2"
              :step="0.1"
              @change="calculateItemAmount(scope.row)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="销售金额" width="120">
          <template #default="scope">
            <span>{{ scope.row.shopOrderMoney.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="120">
          <template #default="scope">
            <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeItem(scope.$index)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="summary-info" style="margin-top: 20px; text-align: right">
        <span>合计：</span>
        <span>货品数量：{{ totalQuantity }}</span>
        <span style="margin-left: 20px">销售金额：{{ totalAmount.toFixed(2) }}</span>
      </div>

      <div class="form-actions" style="margin-top: 30px; text-align: center">
        <el-button type="primary" @click="submitForm">添加</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-card>

    <!-- 货品选择弹窗 -->
    <el-dialog v-model="goodsDialogVisible" title="添加货品" width="80%">
      <div style="margin-bottom: 20px">
        <el-input
          v-model="goodsSearchKeyword"
          placeholder="请输入货品编号/名称"
          style="width: 300px; margin-right: 10px"
        ></el-input>
        <el-select v-model="goodsSearchUnit" placeholder="请选择单位" style="width: 150px; margin-right: 10px">
          <el-option label="瓶" value="瓶"></el-option>
          <el-option label="个" value="个"></el-option>
          <el-option label="箱" value="箱"></el-option>
        </el-select>
        <el-button type="primary" @click="searchGoods">查询</el-button>
        <el-button type="primary" @click="resetGoodsSearch">重置</el-button>
      </div>
      <el-table
        :data="goodsList"
        border
        style="width: 100%"
        @selection-change="handleGoodsSelectionChange"
        height="400"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="goodsCode" label="货品编号" min-width="120" />
        <el-table-column prop="goodsName" label="货品名称" min-width="150" />
        <el-table-column prop="specModel" label="规格型号" min-width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="salePrice" label="入库单价" width="100" />
        <el-table-column prop="currentInventory" label="当前库存" width="100" />
      </el-table>
      <div class="pagination-container" style="margin-top: 20px">
        <el-pagination
          v-model:current-page="goodsPageInfo.pageIndex"
          v-model:page-size="goodsPageInfo.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="goodsPageInfo.total"
          @size-change="handleGoodsSizeChange"
          @current-change="handleGoodsCurrentChange"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="goodsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmGoods">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 表单数据
const shopOrderForm = reactive({
  shopOrderCode: '',
  shopOrderDate: new Date().toISOString().split('T')[0],
  customerId: null,
  customerName: '',
  contact: '',
  contactPhone: '',
  deptId: '',
  deptName: '',
  userId: null,
  userName: '',
  remark: '',
  status: 0,
  shopAllGoods: '', // 所有选择的货品名称
  shopAllNum: 0,
  shopAllMoney: 0
})

// 表单校验规则
const rules = {
  shopOrderDate: [{ required: true, message: '请选择销售日期', trigger: 'change' }],
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  deptId: [{ required: true, message: '请选择销售部门', trigger: 'change' }],
  userId: [{ required: true, message: '请选择销售负责人', trigger: 'change' }]
}

// 销售订单明细
const shopOrderDetails = ref([])
const selectedDetails = ref([])

// 客户选择相关
const customerOptions = ref([])

// 部门选择相关
const departmentOptions = ref([])

// 用户选择相关
const userOptions = ref([])

// 货品选择相关
const goodsDialogVisible = ref(false)
const goodsList = ref([])
const selectedGoods = ref([])
const goodsSearchKeyword = ref('')
const goodsSearchUnit = ref('')
const goodsPageInfo = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 表单引用
const shopOrderFormRef = ref(null)

// 计算属性：总数量和总金额
const totalQuantity = computed(() => {
  return shopOrderDetails.value.reduce((sum, item) => sum + (item.shopOrderNum || 0), 0)
})

const totalAmount = computed(() => {
  return shopOrderDetails.value.reduce((sum, item) => sum + (item.shopOrderMoney || 0), 0)
})

// 生成销售单号
const generateOrderCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  shopOrderForm.shopOrderCode = `XS${year}${month}${day}${hours}${minutes}${seconds}${random}`
}

// 加载客户列表
const loadCustomers = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/ShopOrder/customers')
    if (response.data.code === 200) {
      customerOptions.value = response.data.data
      console.log('客户数据:', response.data.data)
    } else {
      ElMessage.error('获取客户列表失败')
    }
  } catch (error) {
    console.error('获取客户列表出错:', error)
    ElMessage.error('获取客户列表失败')
  }
}

// 加载部门树形数据
const loadDepartments = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/ShopOrder/GetDepartmentTreeSelector')
    if (response.data.code === 200) {
      departmentOptions.value = response.data.data
      console.log('部门数据:', response.data.data)
    } else {
      ElMessage.error('获取部门列表失败')
    }
  } catch (error) {
    console.error('获取部门列表出错:', error)
    ElMessage.error('获取部门列表失败')
  }
}

// 加载用户列表
const loadUsers = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/ShopOrder/users/select?pageIndex=1&pageSize=50')
    if (response.data.code === 200) {
      userOptions.value = response.data.data
      console.log('用户数据:', response.data.data)
      // 检查数据结构
      if (response.data.data.length > 0) {
        console.log('第一个用户的数据结构:', response.data.data[0])
        console.log('用户ID字段(user_ID):', response.data.data[0].user_ID)
        console.log('用户ID字段(user_Id):', response.data.data[0].user_Id)
        console.log('用户名字段:', response.data.data[0].userName)
        console.log('实际使用的ID值:', response.data.data[0].user_Id || response.data.data[0].user_ID)
      }
    } else {
      ElMessage.error('获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表出错:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 加载货品列表
const loadGoods = async () => {
  try {
    const response = await axios.get(
      `http://localhost:8080/api/ShopOrder/GetProductPageList?pageIndex=${goodsPageInfo.pageIndex}&pageSize=${goodsPageInfo.pageSize}`
    )
    if (response.data.code === 200) {
      goodsList.value = response.data.data
      goodsPageInfo.total = response.data.total || response.data.data.length
      console.log('货品数据:', response.data.data)
    } else {
      ElMessage.error('获取货品列表失败')
    }
  } catch (error) {
    console.error('获取货品列表出错:', error)
    ElMessage.error('获取货品列表失败')
  }
}

// 客户变更处理
const handleCustomerChange = (value) => {
  const customer = customerOptions.value.find(item => item.id === value)
  if (customer) {
    shopOrderForm.customerName = customer.customerName
    // 根据接口返回的数据结构自动填充联系信息
    shopOrderForm.contact = customer.contact || ''
    shopOrderForm.contactPhone = customer.contactPhone || ''
    console.log('已选择客户:', customer)
  }
}

// 部门变更处理
const handleDeptChange = (value) => {
  const findDepartment = (departments, value) => {
    for (const dept of departments) {
      if (dept.value === value) {
        return dept
      }
      if (dept.children && dept.children.length > 0) {
        const found = findDepartment(dept.children, value)
        if (found) return found
      }
    }
    return null
  }
  
  const department = findDepartment(departmentOptions.value, value)
  if (department) {
    shopOrderForm.deptName = department.label
    console.log('已选择部门:', department)
  }
}

// 用户变更处理
const handleUserChange = (value) => {
  // 兼容不同的字段名：user_Id 或 user_ID
  const user = userOptions.value.find(item => 
    item.user_Id === value || item.user_ID === value
  )
  if (user) {
    shopOrderForm.userId = value  // 确保userId被正确赋值
    shopOrderForm.userName = user.userName
    console.log('已选择用户:', user, '用户ID:', value)
    console.log('表单userId已更新为:', shopOrderForm.userId)
    console.log('用户对象的ID字段:', user.user_Id || user.user_ID)
  } else {
    console.warn('未找到匹配的用户，value:', value, 'userOptions:', userOptions.value)
  }
}

// 打开货品选择弹窗
const openGoodsDialog = () => {
  goodsDialogVisible.value = true
  goodsPageInfo.pageIndex = 1
  loadGoods()
}

// 货品选择变更处理
const handleGoodsSelectionChange = (selection) => {
  selectedGoods.value = selection
}

// 货品分页大小变更
const handleGoodsSizeChange = (val) => {
  goodsPageInfo.pageSize = val
  loadGoods()
}

// 货品当前页变更
const handleGoodsCurrentChange = (val) => {
  goodsPageInfo.pageIndex = val
  loadGoods()
}

// 搜索货品
const searchGoods = () => {
  goodsPageInfo.pageIndex = 1
  loadGoods()
}

// 重置货品搜索
const resetGoodsSearch = () => {
  goodsSearchKeyword.value = ''
  goodsSearchUnit.value = ''
  goodsPageInfo.pageIndex = 1
  loadGoods()
}

// 确认选择货品
const confirmGoods = () => {
  if (selectedGoods.value.length === 0) {
    ElMessage.warning('请至少选择一个货品')
    return
  }

  // 将选中的货品添加到明细列表
  selectedGoods.value.forEach(good => {
    // 检查是否已存在相同货品
    const existingIndex = shopOrderDetails.value.findIndex(item => item.goodsId === good.id)
    
    if (existingIndex >= 0) {
      // 如果已存在，增加数量
      shopOrderDetails.value[existingIndex].shopOrderNum += 1
      calculateItemAmount(shopOrderDetails.value[existingIndex])
    } else {
      // 如果不存在，添加新项
      const newItem = {
        goodsId: good.id,
        goodsCode: good.goodsCode,
        goodsName: good.goodsName,
        specModel: good.specModel,
        unit: good.unit || '个',
        currentInventory: good.currentInventory || 0,
        shopOrderNum: 1,
        shopOrderPrice: good.salePrice || 0,
        shopOrderMoney: good.salePrice || 0,
        remark: ''
      }
      shopOrderDetails.value.push(newItem)
    }
  })

  // 更新总计
  updateTotals()
  
  goodsDialogVisible.value = false
  ElMessage.success(`已添加 ${selectedGoods.value.length} 个货品到明细`)
}

// 计算单项金额
const calculateItemAmount = (row) => {
  row.shopOrderMoney = (row.shopOrderNum || 0) * (row.shopOrderPrice || 0)
  updateTotals()
}

// 更新总计数据
const updateTotals = () => {
  shopOrderForm.shopAllNum = totalQuantity.value
  shopOrderForm.shopAllMoney = totalAmount.value
  
  // 更新shopAllGoods字段，将所有选中货品的名称拼接起来
  const goodsNames = shopOrderDetails.value.map(item => {
    return `${item.goodsName}(${item.shopOrderNum}${item.unit})`
  })
  shopOrderForm.shopAllGoods = goodsNames.join(', ')
}

// 表格选择变更
const handleSelectionChange = (selection) => {
  selectedDetails.value = selection
}

// 移除选中项
const removeSelectedItems = () => {
  if (selectedDetails.value.length === 0) {
    ElMessage.warning('请选择要移除的项')
    return
  }

  ElMessageBox.confirm('确认移除选中的明细项?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const selectedIds = selectedDetails.value.map(item => item.goodsId)
    shopOrderDetails.value = shopOrderDetails.value.filter(item => !selectedIds.includes(item.goodsId))
    updateTotals()
    ElMessage.success('已移除选中项')
  }).catch(() => {})
}

// 移除单个项
const removeItem = (index) => {
  shopOrderDetails.value.splice(index, 1)
  updateTotals()
}

// 提交表单
const submitForm = async () => {
  if (!shopOrderFormRef.value) return
  
  await shopOrderFormRef.value.validate(async (valid) => {
    if (valid) {
      if (shopOrderDetails.value.length === 0) {
        ElMessage.warning('请至少添加一个销售明细')
        return
      }
      
      // 检查明细数据是否有效
      for (const detail of shopOrderDetails.value) {
        if (!detail.shopOrderNum || detail.shopOrderNum <= 0) {
          ElMessage.warning(`货品 ${detail.goodsName} 的数量必须大于0`)
          return
        }
        if (!detail.shopOrderPrice || detail.shopOrderPrice <= 0) {
          ElMessage.warning(`货品 ${detail.goodsName} 的单价必须大于0`)
          return
        }
      }
      
      try {
        // 准备提交数据
        const submitData = {
          shopOrder: {
            shopOrderCode: shopOrderForm.shopOrderCode,
            shopOrderDate: shopOrderForm.shopOrderDate,
            customerId: Number(shopOrderForm.customerId),
            contact: shopOrderForm.contact,
            contactPhone: shopOrderForm.contactPhone,
            deptId: String(shopOrderForm.deptId),
            userId: Number(shopOrderForm.userId),
            status: 0,
            shopAllGoods: shopOrderForm.shopAllGoods,
            shopAllNum: Number(shopOrderForm.shopAllNum),
            shopAllMoney: Number(shopOrderForm.shopAllMoney),
            remark: shopOrderForm.remark
          },
          shopOrderDetails: shopOrderDetails.value.map(item => ({
            goodsId: Number(item.goodsId),
            shopOrderNum: Number(item.shopOrderNum),
            shopOrderPrice: Number(item.shopOrderPrice),
            shopOrderMoney: Number(item.shopOrderMoney),
            remark: item.remark || ''
          }))
        }
        
        console.log('提交数据:', JSON.stringify(submitData, null, 2))
        
        const response = await axios.post('http://localhost:8080/api/ShopOrder/add-with-details', submitData)
        
        if (response.data && response.data.code === 200) {
          ElMessage.success('添加销售订单成功')
          router.push('/ShopOrderView')
        } else {
          ElMessage.error(`添加失败: ${response.data?.message || '未知错误'}`)
        }
      } catch (error) {
        console.error('提交表单出错:', error)
        console.log('错误状态码:', error.response?.status)
        console.log('错误数据:', error.response?.data)
        ElMessage.error(`添加失败: ${error.response?.data?.message || error.message || '未知错误'}`)
      }
    } else {
      ElMessage.warning('请填写必填项')
    }
  })
}

// 返回列表页
const goBack = () => {
  router.push('/ShopOrderView')
}

// 页面加载时初始化
onMounted(() => {
  console.log('页面初始化，shopOrderForm.userId初始值:', shopOrderForm.userId)
  generateOrderCode()
  loadCustomers()
  loadDepartments()
  loadUsers()
})
</script>

<style scoped>
.shop-order-edit {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.button-container {
  margin-bottom: 15px;
}
.summary-info {
  font-weight: bold;
  font-size: 16px;
}
</style>